package sort;

import java.util.Arrays;

/**
 * 排序算法
 */
public class Algorithm {
    public static void main(String[] args) {
//        bubbleSort();
//        selectionSort();
//        insertionSort();
        insertShell();
    }
    static int[] num = new int[]{2, 3, 1, 3, 4, 6};
    /**
     * 交换排序-冒泡排序
     */
    public static void bubbleSort() {
//        int[] num = new int[]{2, 3, 1, 3, 4, 6};
        int len = num.length; // 6
        for (int i = 0; i < len; i++) {
            for (int j = 0; j < len - i -1; j++) {
                if (num[j + 1] < num[j]) {
                    int temp = num[j + 1];
                    num[j + 1] = num[j];
                    num[j] = temp;
                }
            }
        }
        System.out.println(Arrays.toString(num));
    }

    /**
     * 选择排序-简单选择
     */
    public static void selectionSort() {
        int len = num.length;
        for (int i = 0; i < len -1; i++) {
            int min = num[i];
            int minIndex = i;
            for (int j = i +1; j < len; j++) {
                if (min > num[j]) { // 找最小元素和所在索引
                   min = num[j];
                   minIndex = j;
                }
            }
            // 交换元素
            num[minIndex] = num[i];
            num[i] = min;
        }
        System.out.println(Arrays.toString(num));
    }
    /**
     * 选择排序-简单排序-myself
     */
    public static void selectionSort1() {
        int len = num.length;
        for (int i = 0; i < len; i++) {
            for (int j = i +1; j < len -1; j++) {
                if (num[i] > num[j]) {
                    int temp = num[j];
                    num[j] = num[i];
                    num[i] = temp;
                }
            }
        }
        System.out.println(Arrays.toString(num));
    }

    /**
     * 插入排序-简单插入
     */
    public static void insertionSort(){
        int len = num.length;
        for (int i = 1; i < len; i++) {
            int currValue = num[i];
            int insertIndex = i - 1;
            while (insertIndex >= 0 && currValue < num[insertIndex]) {
                num[insertIndex + 1] = num[insertIndex];
                insertIndex--;
            }
            num[insertIndex + 1] = currValue;  //index:1 vlaue=2; 2 < 1; num[insertIndex+1] = currValue
        }
        System.out.println(Arrays.toString(num));
    }

    /**
     * 插入排序-希尔排序
     */
    public static void insertShell(){
        int[] num = {8, 9, 1, 7, 2, 3, 5, 4, 6, 0};
        int len = num.length;
        int temp = 0;
        for (int gap = len/2; gap > 0; gap/=2) {
            for (int i = gap; i < len; i++) {
                for (int j = i - gap; j >= 0; j-=gap) {
                    if(num[j] > num[j+ gap]){
                        temp = num[j];
                        num[j] = num[j+gap];
                        num[j + gap] = temp;
                    }
                }
            }
        }
        System.out.println(Arrays.toString(num));
    }
}
